<template>
  <div class="flex flex-col h-full bg-blue-50/50 rounded-lg p-4">
    <!-- 对话记录区域 -->
    <div 
      ref="chatContainer" 
      class="flex-1 overflow-y-auto mb-4 space-y-4 p-4"
    >
      <div
        v-for="message in messages"
        :key="message.id"
        class="flex"
        :class="message.role === 'assistant' ? 'justify-start' : 'justify-end'"
      >
        <!-- 消息气泡 -->
        <div 
          class="max-w-[80%] rounded-lg p-4 shadow-sm"
          :class="[
            message.role === 'assistant' 
              ? 'bg-white mr-auto' 
              : 'bg-blue-500 text-white ml-auto'
          ]"
        >
          <!-- Markdown 内容 -->
          <div 
            v-if="message.type === 'text'"
            class="markdown-body"
            :class="{ 'text-white': message.role === 'user' }"
            v-html="renderMarkdown(message.content)"
          ></div>

          <!-- 图片内容 -->
          <div 
            v-else-if="message.type === 'image'"
            class="space-y-2"
          >
            <img 
              v-for="file in message.files"
              :key="file.url"
              :src="file.url"
              class="max-w-full rounded-lg"
              :alt="file.name"
            />
          </div>

          <!-- 文件内容 -->
          <div 
            v-else-if="message.type === 'file'"
            class="space-y-2"
          >
            <div 
              v-for="file in message.files"
              :key="file.url"
              class="flex items-center space-x-2 p-2 bg-gray-50 rounded"
            >
              <icon-file />
              <span>{{ file.name }}</span>
              <a-button 
                type="text" 
                size="mini"
                @click="downloadFile(file)"
              >
                下载
              </a-button>
            </div>
          </div>

          <!-- 发送状态 -->
          <div 
            v-if="message.status === 'sending'"
            class="text-xs mt-1"
            :class="message.role === 'user' ? 'text-blue-200' : 'text-gray-400'"
          >
            正在输入... <a-spin :size="12" />
          </div>
          
          <div 
            v-if="message.status === 'error'"
            class="text-xs mt-1 text-red-500"
          >
            发送失败: {{ message.error }}
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="bg-white rounded-lg shadow-sm p-4">
      <!-- 文件预览区 -->
      <div v-if="previewFile" class="mb-3">
        <div class="relative inline-block group">
          <!-- 图片预览 -->
          <div 
            v-if="previewFile.type.startsWith('image/')"
            class="relative w-24 h-24 rounded-lg overflow-hidden cursor-pointer"
            @click="showImagePreview"
          >
            <img 
              :src="previewFile.url" 
              class="w-full h-full object-cover"
              :alt="previewFile.name"
            />
          </div>

          <!-- 文件预览 -->
          <div 
            v-else
            class="relative w-24 h-24 rounded-lg bg-gray-100 flex flex-col items-center justify-center cursor-pointer"
            @click="showFileInfo"
          >
            <icon-file class="text-2xl text-gray-500" />
            <span class="text-xs text-gray-600 mt-1 px-2 truncate max-w-full">
              {{ previewFile.name }}
            </span>
          </div>

          <!-- 删除按钮 -->
          <a-button
            type="text"
            size="mini"
            class="absolute -top-1 -right-1 opacity-0 group-hover:opacity-100 transition-opacity"
            @click.stop="removePreviewFile"
          >
            <icon-close />
          </a-button>
        </div>
      </div>

      <!-- 输入工具栏 -->
      <div class="flex space-x-2">
        <!-- 语音输入按钮 -->
        <a-button 
          type="text" 
          class="flex items-center"
          @click="startVoiceInput"
        >
          <icon-voice />
        </a-button>

        <!-- 输入框 -->
        <a-textarea
          v-model="inputMessage"
          :auto-size="{ minRows: 1, maxRows: 6 }"
          placeholder="输入消息，Shift + Enter 换行，Enter 发送"
          class="flex-1"
          @keydown.enter.prevent="handleEnter"
        />

        <!-- 上传按钮 -->
        <a-upload
          accept="image/*,.pdf,.doc,.docx"
          :show-file-list="false"
          @change="handleFileUpload"
        >
          <a-button type="text">
            <icon-upload />
          </a-button>
        </a-upload>

        <!-- 发送按钮 -->
        <a-button 
          type="primary"
          :loading="sending"
          @click="sendMessage"
        >
          发送
        </a-button>
      </div>
    </div>

    <!-- 图片预览弹窗 -->
    <a-modal
      v-model:visible="imagePreviewVisible"
      footer-less
      :mask-closable="true"
    >
      <img 
        v-if="previewFile?.type.startsWith('image/')"
        :src="previewFile.url"
        class="max-w-full max-h-[80vh]"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { Message } from '@arco-design/web-vue'
import { 
  IconImage, 
  IconFile,
  IconVoice,
  IconUpload,
  IconClose
} from '@arco-design/web-vue/es/icon'
import type { ChatMessage } from '@/types'
import { useAppStore } from '../store'
import { useSettingsStore } from '../store/settings'
import { initOpenAI, streamChat } from '../services/openai'

// 配置 marked
marked.setOptions({
  highlight: (code, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value
    }
    return code
  },
  breaks: true
})

const store = useAppStore()
const settingsStore = useSettingsStore()
const messages = ref<ChatMessage[]>([])
const inputMessage = ref('')
const chatContainer = ref<HTMLElement | null>(null)
const sending = ref(false)

// 渲染 Markdown
const renderMarkdown = (content: string) => {
  return marked(content)
}

// 处理回车键
const handleEnter = (e: KeyboardEvent) => {
  if (e.shiftKey) return
  sendMessage()
}

// 文件预览相关
interface PreviewFile {
  url: string
  type: string
  name: string
}

const previewFile = ref<PreviewFile | null>(null)
const imagePreviewVisible = ref(false)

// 处理文件上传
const handleFileUpload = (info: any) => {
  if (info.file.status === 'done') {
    // 设置预览文件
    previewFile.value = {
      url: URL.createObjectURL(info.file.originFile),
      type: info.file.type,
      name: info.file.name
    }
  }
}

// 移除预览文件
const removePreviewFile = () => {
  if (previewFile.value) {
    URL.revokeObjectURL(previewFile.value.url)
    previewFile.value = null
  }
}

// 显示图片预览
const showImagePreview = () => {
  if (previewFile.value?.type.startsWith('image/')) {
    imagePreviewVisible.value = true
  }
}

// 显示文件信息
const showFileInfo = () => {
  if (previewFile.value) {
    Message.info(`文件名：${previewFile.value.name}`)
  }
}

// 发送消息
const sendMessage = async () => {
  // 如果有预览文件，添加到消息中
  if (previewFile.value) {
    messages.value.push({
      id: Date.now().toString(),
      role: 'user',
      content: '',
      type: previewFile.value.type.startsWith('image/') ? 'image' : 'file',
      timestamp: Date.now(),
      status: 'success',
      files: [previewFile.value]
    })
    removePreviewFile()
    scrollToBottom()
    return
  }
  
  if (!inputMessage.value.trim() || sending.value) return

  // 检查 API Key
  if (!settingsStore.settings.openAIKey) {
    Message.error('请先配置 OpenAI API Key')
    return
  }
  
  const message: ChatMessage = {
    id: Date.now().toString(),
    role: 'user',
    content: inputMessage.value,
    type: 'text',
    timestamp: Date.now(),
    status: 'sending'
  }

  messages.value.push(message)
  inputMessage.value = ''
  sending.value = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    // 初始化 OpenAI
    initOpenAI(settingsStore.settings.openAIKey)
    
    // 创建 AI 回复消息
    const aiMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'assistant',
      content: '',
      type: 'text',
      timestamp: Date.now(),
      status: 'sending'
    }
    messages.value.push(aiMessage)
    
    // 使用 stream 接收回复
    await streamChat(
      message.content,
      messages.value,
      (text: string) => {
        aiMessage.content += text
        scrollToBottom()
      }
    )
    
    aiMessage.status = 'success'
    message.status = 'success'
  } catch (error: any) {
    message.status = 'error'
    message.error = error.message
    Message.error('发送失败')
  } finally {
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 开始语音输入
const startVoiceInput = () => {
  // TODO: 实现语音输入
  Message.info('语音输入功能开发中')
}

onMounted(() => {
  // 加载历史消息
  // TODO: 从存储中加载历史消息
})

// 清理工作
onUnmounted(() => {
  // 清理预览文件
  if (previewFile.value) {
    URL.revokeObjectURL(previewFile.value.url)
  }
  // 清理文件 URL
  messages.value.forEach(message => {
    if (message.files) {
      message.files.forEach(file => {
        URL.revokeObjectURL(file.url)
      })
    }
  })
})
</script>

<style>
/* Markdown 样式 */
.markdown-body {
  font-size: 14px;
  line-height: 1.6;
}

.markdown-body code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
}

.markdown-body pre code {
  background-color: transparent;
  padding: 0;
}

/* 用户消息中的 Markdown */
.text-white .markdown-body {
  color: white;
}

.text-white .markdown-body code {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

/* 预览区域样式 */
.group:hover .opacity-0 {
  opacity: 1;
}
</style> 